﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using LightLibrary;

namespace LightLibraryUnity {
	public partial class FormRoot : Form {
		public FormRoot() {
			InitializeComponent();
		}

		private void oPENToolStripMenuItem_Click(object sender, EventArgs e) {
			var path = IOTools.GetDirectoryPath();
			if (!string.IsNullOrEmpty(path)) {
				var rootFolder = new DirectoryInfo(path);
				var files = IOTools.GetAllFiles(rootFolder);
				files.Sort(ArrayTools.ComparisonByFileSize);
				FilleView(files.ToArray());
				/*
				var msg = "";
				FileInfo lastFile = null;
				for (var i = 1; i < files.Count; i++) {
					if (files[i].Length == files[i - 1].Length) {
						if (lastFile == null) {
							msg += files[i - 1].Length + "\n";
							msg += files[i - 1].FullName + "\n";
						}
						msg += files[i].FullName + "\n";
						lastFile = files[i];
					} else if (lastFile != null) {
						lastFile = null;
						msg += "\n";
					}
				}
				using (FileStream fs = File.Create("Result.txt")) {
					// Add some text to file
					Byte[] title = new UTF8Encoding(true).GetBytes(msg);
					fs.Write(title, 0, title.Length);
				}
				MessageBox.Show("Done");*/
			}
		}

		private void FilleView(FileInfo[] fis) {
			var items = GetViewItens(fis);

			listViewFileInfo.BeginUpdate();
			listViewFileInfo.ListViewItemSorter = null;
			listViewFileInfo.Items.AddRange(items);
			listViewFileInfo.EndUpdate();
		}

		private ListViewItem[] GetViewItens(FileInfo[] fis) {
			var result = new ListViewItem[fis.Length];
			FileInfo fi;
			ListViewItem viewItem;
			for (var i = 0; i < fis.Length; i++) {
				fi = fis[i];
				viewItem = new ListViewItem(new[] { "", fi.Length.ToString(), fi.Name, fi.FullName });
				result[i] = viewItem;
			}
			return result;
		}

		private void MenuLibraryNew_Click(object sender, EventArgs e) {
			var formLibraryNew = new FormLibraryNew();
			formLibraryNew.Show();
		}

		private void MenuLibraryImportFolder_Click(object sender, EventArgs e) {
			if (Library.Instance.Work == null) {
				return;
			}
			var directoryPath = IOTools.GetDirectoryPath();
			Library.Instance.Work.ImportFolder(directoryPath);
		}
	}
}
